package com.suxin.shiro.jwt.controller;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Tang
 * @classname JwtUtils
 * @description [  ]
 * @date 2021/3/21 21:57
 */
public class JwtUtils {

    private static final String PRIVATE_KEY = "7786df7fc3a34e26a61c034d5ec8245d";
    // 过期时间 单位分钟
    private static final Integer EXPIRATION_TIME = 60;

    /**
     * 获取一个token
     *
     * @param claims
     * @return
     */
    public static String generateToken(Map<String, Object> claims) {
        // 创建token时间
        claims.put("createTime",
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        return Jwts.builder()
                .addClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME * 1000 * 60))
                .signWith(generalKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public static Jws<Claims> parseJwt(String jwtString) {
        Key key = generalKey();
        try {
            return Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(jwtString);
        } catch (ExpiredJwtException e) {
            System.out.println( "token 过期了...." );
            return null;
        }
    }

    public static Map<String, Object> getInfoFromToken(String token) {
        Jws<Claims> claimsJws = parseJwt(token);
        if (claimsJws == null) {
            return null;
        }
        // 自定义逻辑
        Object id = claimsJws.getBody().get("id");
        String username = (String) claimsJws.getBody().get("username");
        Map<String, Object> hashMap = new HashMap<>(8);
        hashMap.put("id", id);
        hashMap.put("username", username);
        return hashMap;
    }

    private static Key generalKey(){
        return Keys.hmacShaKeyFor(PRIVATE_KEY.getBytes());
    }
}